package com.tz.crm.dao.impl;


import com.tz.crm.dao.UserDao;
import com.tz.crm.entity.Role;
import com.tz.crm.entity.User;
import com.tz.crm.utils.Pager;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * UserDaoImpl
 */
@Repository
@Transactional
@SuppressWarnings("unchecked")
public class UserDaoImpl extends BaseDaoImpl<User, String> implements UserDao {

    @SuppressWarnings("unchecked")
    @Override
    public List<User> getByName(String realName) {
        String hql = "from User u where u.realName like :name";
        return getSession().createQuery(hql)
                .setParameter("name", "%" + realName + "%")
                .list();
    }

    @Override
    public User login(String username, String password) {
        String hql = "from User u join fetch u.roleSet where lower(u.username) = :username and u.password = :password";
        return (User) getSession().createQuery(hql)
                .setParameter("username", username.toLowerCase())
                .setParameter("password", password)
                .uniqueResult();
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<User> getByDepartmentName(String name, Pager pager) {
        //todo:use pager
        String hql = "from User u where u.dept.deptName = :name";
        return getSession().createQuery(hql)
                .setParameter("name", name)
                .list();
    }

    @Override
    public List<User> getAll(Pager pager) {
        if (pager == null) {
            pager = new Pager();
        }
        String hql = "from User u order by u.realName asc";
        return getSession().createQuery(hql)
                .setFirstResult((pager.getPageNumber() - 1) * pager.getPageSize())
                .setMaxResults(pager.getPageSize())
                .list();
    }

    @Override
    public List<User> getAll() {
        String hql = "from User u order by u.realName asc";
        return getSession().createQuery(hql).list();
    }

    @Override
    public List<Role> getRolesById(int id) {
        String hql = "from User join fetch u.roleSet where u.id:=id";
        List<Role> list = getSession().createQuery(hql).setParameter("id", id)
                .list();
        return list;
    }
}
